import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../components/login.vue'
import Home from '../components/Home.vue'
import Welcome from '../components/Welcome.vue'
import Users from '../components/user/Users.vue'
Vue.use(VueRouter)

const routes = [
    {
        path: '/',
        name: 'hello',
        component: Login
    },
    {
        path: '/login',
        name: 'hello',
        component: Login
    },
    {
        path: '/home',
        name: 'hello',
        component: Home,
        // 重新定向
        redirect:'/welcome',
        children: [
            {
                path: '/welcome',
                name: 'hello',
                component: Welcome,
            },
            {
                path: '/users',
                name: 'hello',
                component: Users,
            },
        ]
    },
]
const router = new VueRouter({
    routes
})



// 挂载路由导航守卫,挂载方法：为router对象调用一个bef``函数，然后bbof接收一个回调函数，那么我们写一个箭头函数，在回调函数的形参中有三个参数，分别是to、from、next
router.beforeEach((to, from, next) => {
    // to 将要访问的路径    from 代表从哪个路径跳转而来  next是一个函数，表示放行，两种调用方式1.next（）直接放行  2.next('/login)强制跳转到指定页面
    if (to.path === '/login') return next()
    // 获取token
    const tokenStr = window.sessionStorage.getItem('token')
    if (!tokenStr) return next('/login')
    next()

})



export default router
